//
//  SWPaintBlurViewController.swift
//  PhotoEditorFactory
//
//  Created by linhan on 16/8/4.
//  Copyright © 2016年 test. All rights reserved.
//

import Foundation
import UIKit
class SWPaintBlurViewController: SWBaseViewController,CGImageDrawCanvasDelegate
{
    weak var image:UIImage?
    weak var delegate:SWImageProcessViewControllerDelegate?
    
    private let BlurAmount:CGFloat = 45
    private var _blurRadius:CGFloat = 6
    
    private var _originImageView:UIImageView = UIImageView()
    private var _blurImageView:UIImageView = UIImageView()
    
    private var _canvas:SWDrawMaskCanvas?
    private var _cursor:UIView = UIView()
    
    private var _container:UIView = UIView()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setup()
    }
    
    var lineWidth:CGFloat = 40{
        didSet{
            let Radius:CGFloat = BlurAmount * 0.3 + lineWidth * 0.5
            _cursor.frame = CGRectMake(0, 0, Radius * 2, Radius * 2)
            _cursor.center = _container.bounds.center
            _cursor.layer.cornerRadius = Radius
            _canvas?.lineWidth = lineWidth
        }
    }
    
    deinit
    {
        print("DEINIT SWPaintBlurViewController")
    }
    
    private func setup()
    {
        view.backgroundColor = UIColor.white
        
        view.addSubview(_container)
        
        doodleBlurTest()
        
        createNavigationLeftCustomButton(nil, image: UIImage(named: "editor_icon_cancel"), target: self, action: #selector(cancelBtnTapped))
        createNavigationRightCustomButton(nil, image: UIImage(named: "editor_icon_ok"), target: self, action: #selector(confirmBtnTapped))
        
        
        let SCHeight:CGFloat = 60
        let SCBottomMargin:CGFloat = 15
        let segmentedControl:UISegmentedControl = UISegmentedControl(items: ["清", "糊"])
        segmentedControl.frame = CGRectMake(0, view.height - SCHeight - SCBottomMargin, 60, SCHeight)
        segmentedControl.selectedSegmentIndex = 0
        segmentedControl.addTarget(self, action: #selector(segmentedControlValueChanged(_:)), for: UIControlEvents.valueChanged)
        view.addSubview(segmentedControl)
        
        let SliderX:CGFloat = segmentedControl.right + 15
        let strokeSlider:UISlider = UISlider(frame: CGRectMake(SliderX, segmentedControl.y, view.width - 15 - SliderX, 30))
        strokeSlider.maximumValue = 100
        strokeSlider.value = 40
        strokeSlider.minimumValue = 25
        strokeSlider.addTarget(self, action: #selector(sliderValueChange(_:)), for: .valueChanged)
        strokeSlider.addTarget(self, action:#selector(sliderTouchUpInside(_:)), for:.touchUpInside)
        strokeSlider.addTarget(self, action:#selector(sliderTouchUpOutside(_:)), for:.touchUpOutside)
        strokeSlider.addTarget(self, action:#selector(sliderTouchDown(_:)), for:.touchDown)
        view.addSubview(strokeSlider)
        
        let strengthSlider:UISlider = UISlider(frame: CGRectMake(SliderX, strokeSlider.bottom + 10, strokeSlider.width, 30))
        strengthSlider.maximumValue = 12
        strengthSlider.value = Float(_blurRadius)
        strengthSlider.minimumValue = 1
        strengthSlider.addTarget(self, action:#selector(strengthSliderTouchUp(_:)), for:.touchUpInside)
        strengthSlider.addTarget(self, action:#selector(strengthSliderTouchUp(_:)), for:.touchUpOutside)
        view.addSubview(strengthSlider)
        
        
        _cursor.layer.borderColor = UIColor.darkGray.cgColor
        _cursor.layer.borderWidth = 1.5
        _cursor.layer.masksToBounds = true
        _cursor.isHidden = true
        
        lineWidth = CGFloat(strokeSlider.value)
    }
    private var _canvasScale:CGFloat = 1
    private func doodleBlurTest()
    {
        if let blurImage = image?.blurredImage(_blurRadius, iterations: 3, ratio: 1, blendColor: nil, blendMode: .normal)
        {
            let width:CGFloat = view.width
            let height:CGFloat = view.height
            let scale:CGFloat = ViewUtil.getAdaptiveScale(blurImage.size.width, targetH: blurImage.size.height, containerW: width, containerH: height)
            let imageWidth:CGFloat = blurImage.size.width * scale
            let imageHeight:CGFloat = blurImage.size.height * scale
            let x:CGFloat = (width - imageWidth) * 0.5
            let y:CGFloat = (height - imageHeight) * 0.5
            let rect:CGRect = CGRectMake(x, navigationBarBottom, imageWidth, imageHeight).integral
            
            
            _canvasScale = scale
            _container.frame = rect
            
            _blurImageView.image = blurImage
            _blurImageView.frame = _container.bounds
            _container.addSubview(_blurImageView)
            
            let imageView:UIImageView = UIImageView(image: image)
            imageView.frame = _container.bounds
            _container.addSubview(imageView)
            
            let canvas = SWDrawMaskCanvas(frame: _container.bounds)
            canvas.delegate = self
            canvas.blurAmount = BlurAmount
            canvas.backgroundColor = UIColor.clear
            canvas.lineWidth = lineWidth
            _container.addSubview(canvas)
            _canvas = canvas
            
            let layer:CALayer = canvas.shapeLayer
            let loveLayer:CAReplicatorLayer = CAReplicatorLayer()
            loveLayer.instanceCount = 3
            loveLayer.addSublayer(layer)
            
            imageView.layer.mask = loveLayer
            //view.layer.addSublayer(loveLayer)
            
            _container.addSubview(_cursor)
            
        }
        
    }
    
    func CGImageDrawCanvasDrawBegan(_ canvas:SWDrawMaskCanvas, point:CGPoint)
    {
        _cursor.isHidden = false
        _cursor.center = CGPointMake(point.x + _blurImageView.x, point.y + _blurImageView.y)
    }
    
    func CGImageDrawCanvasDrawMoved(_ canvas:SWDrawMaskCanvas, point:CGPoint)
    {
        _cursor.center = CGPointMake(point.x + _blurImageView.x, point.y + _blurImageView.y)
    }
    
    func CGImageDrawCanvasDrawEnded(_ canvas:SWDrawMaskCanvas, point:CGPoint?)
    {
        _cursor.isHidden = true
    }
    
    @objc private func sliderValueChange(_ slider:UISlider)
    {
        lineWidth = CGFloat(slider.value)
    }
    
    @objc private func sliderTouchDown(_ slider:UISlider)
    {
        _cursor.center = _blurImageView.center
        _cursor.isHidden = false
    }
    
    @objc private func sliderTouchUpInside(_ slider:UISlider)
    {
        _cursor.isHidden = true
    }
    
    @objc private func sliderTouchUpOutside(_ slider:UISlider)
    {
        _cursor.isHidden = true
    }
    
    @objc private func strengthSliderTouchUp(_ slider:UISlider)
    {
        _blurRadius = CGFloat(slider.value)
        _blurImageView.image = image?.blurredImage(_blurRadius, iterations: 3, ratio: 1, blendColor: nil,blendMode: CGBlendMode.normal)
    }
    
    @objc private func segmentedControlValueChanged(_ segmentedControl:UISegmentedControl)
    {
        let index:Int = segmentedControl.selectedSegmentIndex
        _canvas?.drawMode = index == 0 ? DrawMode.Draw : DrawMode.Erase
    }
    
    @objc private func cancelBtnTapped()
    {
        dismiss(animated:false, completion: nil)
    }
    
    @objc private func confirmBtnTapped()
    {
        if let image = _container.snapshotImage()
        {
            let result:UIImage = image.imageScaled(toConstrainSize: image.originSize).retinaImage ?? image
            delegate?.imageProcessViewController(controller: self, didFinishProcessImage: result, additionInfo: nil)
            dismiss(animated:false, completion: nil)
            /**
            let scale = 1 / _canvasScale
            print("image:", image.size, image.scale)
            let newSize = CGSizeMake(image.size.width * scale, image.size.height * scale)
            let newImage = ImageUtil.resize(image, size: newSize)
            print("newImage:", newImage.size, newImage.scale)
             **/
        }
    }
    
}



